package cc.lucien.web.controller;

import cc.lucien.web.entity.Admin;
import cc.lucien.web.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
@SessionAttributes(value = {"admin","error"})
public class AdminController {

    @Autowired
    private AdminService adminService;

    //去到登录页
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "admin/admin_login2";
    }

    //登录校验
    @RequestMapping("/login")
    public String login(String username, String password, Map<String, Object> map){
        Admin admin = adminService.getAdminByUsernameAndPassword(username, password);
        if (admin != null && admin.getName() != null) {
            //登录成功
            map.put("admin", admin);
            return "admin/index";
        } else {
            map.put("error", "用户名或密码不匹配！");
            return "redirect:/admin/toLogin";
        }
    }

    // 返回页面
    @RequestMapping("/getIndexV3")
    public String getIndexV3(){
        return "admin/index_v3";
    }

    // 查询所有管理员
    @RequestMapping("/selectAllAdmins")
    public String selectAllAdmins(Map<String,Object> map){
        List<Admin> adminList = adminService.selectAllAdmins();
        map.put("adminList", adminList);
        return "admin/admin/admin_list";
    }

    // 去到添加页面
    @RequestMapping("/toAddAdmin")
    public String toAddAdmin(){
        return "admin/admin/admin_add";
    }

    // 保存添加的管理员
    @RequestMapping("/adminSave")
    public String adminSava(Admin admin, Map<String, Object> map){
        adminService.adminSave(admin);
        map.put("addMsg", "添加管理员成功!");
        return "forward:/admin/selectAllAdmins";
    }

    // 删除管理员
    @RequestMapping("/deleteAdmin")
    public String deleteAdmin(Integer id, Map<String, Object> map){
        adminService.deleteAdmin(id);
        map.put("deleteMsg", "删除成功！");
        // return "redirect:/admin/selectAllAdmins";
        return "forward:/admin/selectAllAdmins";
    }

    // 去修改该管理员信息
    @RequestMapping("/toUpdate")
    public String toUpdate(Integer id, Map<String, Object> map){
        Admin admin = adminService.selectAdminById(id);
        map.put("adminUpdate", admin);
        return "admin/admin/admin_update";
    }

    // 将修改信息保存到数据库
    @RequestMapping("/adminUpdate")
    public String adminUpdate(Admin admin, Map<String, Object> map) {
        adminService.adminUpdate(admin);
        map.put("updateMsg", "修改成功！");
        return "forward:/admin/selectAllAdmins";
    }

}
